package utils

import (
	"github.com/go-resty/resty/v2"
	"log/slog"
	"path/filepath"
	"sync"
)

func Down(downloadDir string, fileUrl string, wg *sync.WaitGroup, ch chan struct{}) {
	defer func() {
		<-ch
		wg.Done()
	}()

	filename, _ := GetFileNameFromURL(fileUrl)
	originPath := filepath.Join(downloadDir, filename)

	//Exist
	if CheckFileExistence(originPath) {
		slog.Info("文件已经存在", "file", filename)
		return
	}

	client := resty.New()
	client.SetOutputDirectory(downloadDir)
	client.SetHeaders(map[string]string{
		"Content-Type": "application/json",
		"User-Agent":   Conf.UserAgent,
	})
	_, downErr := client.R().SetOutput(filename).Get(fileUrl)
	if downErr != nil {
		slog.Error("Error Download", "url", fileUrl, "Error", downErr)
		return
	}

	slog.Info("Success Download:", "url", fileUrl)
}

func OnlyDown(downloadDir string, fileUrl string) string {
	filename, _ := GetFileNameFromURL(fileUrl)
	originPath := filepath.Join(downloadDir, filename)

	//Exist
	if CheckFileExistence(originPath) {
		slog.Info("文件已经存在", "file", filename)
		return ""
	}

	client := resty.New()
	client.SetOutputDirectory(downloadDir)
	client.SetHeaders(map[string]string{
		"Content-Type": "application/json",
		"User-Agent":   Conf.UserAgent,
	})
	_, downErr := client.R().SetOutput(filename).Get(fileUrl)
	if downErr != nil {
		slog.Error("Error Download", "url", fileUrl, "Error", downErr)
		return ""
	}

	slog.Info("Success Download:", "url", fileUrl)

	return filepath.Join(downloadDir, filename)
}
